package BlockingQueue_12;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class 生产者_消费者模型_ArrayBlockingQueue {
    public static void main(String[] args) {
        final int CAPACITY = 5;
        final BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(CAPACITY);
        final int PRODUCER_COUNT = 3;
        final int CONSUMER_COUNT = 2;
        final int ITEMS_PER_PRODUCER = 10;

        // 生产者线程
        for (int i = 0; i < PRODUCER_COUNT; i++) {
            final int producerId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        for (int j = 0; j < ITEMS_PER_PRODUCER; j++) {
                            int item = producerId * 100 + j;
                            queue.put(item); // 阻塞直到有空间可用
                            System.out.println("生产者 " + producerId + " 生产: " + item);
                            Thread.sleep((long)(Math.random() * 200)); // 模拟生产时间
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "生产者-" + i).start();
        }

        // 消费者线程
        for (int i = 0; i < CONSUMER_COUNT; i++) {
            final int consumerId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        while (true) {
                            Integer item = queue.take(); // 阻塞直到有元素可用
                            System.out.println("消费者 " + consumerId + " 消费: " + item);
                            Thread.sleep((long)(Math.random() * 300)); // 模拟处理时间
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "消费者-" + i).start();
        }
    }
}